package com.rzjm.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.WxTemplateDao;
import com.rzjm.api.entity.*;
import com.rzjm.api.service.*;
import com.rzjm.api.util.DateUtil;
import com.rzjm.api.util.WxMessage;
import com.rzjm.api.util.power.RequestSignUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


@Service
public class WxTemplateServiceImpl extends BaseServiceImpl<WxTemplateDao, WxTemplate> implements WxTemplateService {
    @Resource
    private DepartmentService departmentService;

    @Value("${web.appidCy}")
    private String appidCy;//图片地址
    @Value("${web.secretCy}")
    private String secretCy;//图片地址

    @Value("${web.appid_mp_cy}")
    private String appidMpCy;//图片地址

    @Value("${web.secret_mp_cy}")
    private String secretMpCy;//图片地址


    @Resource
    private UserMpService userMpService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserService userService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ShopService shopService;
    @Resource
    private ParameterService parameterService;

    /**
     *  设备离线
     * @param device
     * @return
     */
    @Override
    public int sendWxMsgOffline(Device device, String accessToken) {
        try{
            Shop shop = shopService.selectById(device.getShopId());
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("shop_id", device.getShopId())
                    .and(wrapper -> wrapper.eq("user_type", 4).or().eq("user_type", 6));
            List<SysUser> sysUsers = sysUserService.list(qw);
            if(sysUsers != null && sysUsers.size() > 0){
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && sysUser.getIsSendMsg() == 1 && StrUtil.isNotEmpty(user.getUnionId())){
                                WxMsgTemplate template = getTemplateOffline(device,shop,user);
                                String param = JSONUtil.parseObj(template).toString();
                                System.out.println("accessToken:" + accessToken);
                                if(StrUtil.isNotEmpty(accessToken)){
                                    WxMessage.sendMsg(accessToken,param);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
        return 1;
    }

    private WxMsgTemplate getTemplateOffline(Device device,Shop shop,User user){
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",6);
        QueryWrapper<UserMp> qw = new QueryWrapper<>();
        qw.eq("unionid",user.getUnionId());
        qw.eq("mp_type","cy");
        UserMp userMp = userMpService.getOne(qw);
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/device/index");
            template.setMiniprogram(miniprogram);

            Map<String, MsgTempData> m = new HashMap<>();

//            {{first.DATA}}
//            设备编号：{{keyword1.DATA}}
//            设备名称：{{keyword2.DATA}}
//            设备地址：{{keyword3.DATA}}
//            离线时间：{{keyword4.DATA}}
//            {{remark.DATA}}
//
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有设备已离线，请及时查验");
            m.put("first",first);

            //设备编号
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(device.getDeviceNum());
            m.put("keyword1",keyword1);

            //设备名称
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getSpicalFontColor());
            keyword2.setValue(device.getDeviceName());
            m.put("keyword2",keyword2);

            //设备地址
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            if(shop!=null){
                keyword3.setValue(shop.getShopName());
            }else{
                keyword3.setValue("");
            }
            m.put("keyword3",keyword3);

            //离线时间
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue(DateUtil.getTime(new Date()));
            m.put("keyword4",keyword4);

            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("请尽快检查设备相关情况，及时处理，以免造成损失。");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    @Override
    public void sendWxMsgUseDeviceReg(DeviceWeldingRecord record, DeviceWelding device,FireWork fireWork, int isSafe) {
        try{
            Shop company = shopService.findById(device.getShopId());
            if(company != null){
                //当前，只需要给肾器官作业票选中的安全员推送通知
                List<SysUser> sysUsers = new ArrayList<>();
                QueryWrapper<SysUser> qw = new QueryWrapper<>();
                if(fireWork!= null){
                    qw.eq("user_id",fireWork.getSafeSysUserId());
                    sysUsers = sysUserService.list(qw);
                }else{
                    Department departmentSafe = departmentService.getSafeDepart(device.getShopId());
                    if(departmentSafe != null) {
                        qw.eq("shop_id", device.getShopId());
                        qw.eq("dept_id", departmentSafe.getId());
                        qw.eq("status", 1);
                        sysUsers = sysUserService.list(qw);
                    }
                }

                if(sysUsers != null && sysUsers.size() > 0){
                    for(SysUser sysUser : sysUsers){
                        List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                        if(users != null){
                            for (User user :users){
                                if(user != null && StrUtil.isNotEmpty(user.getUnionId())){
                                    QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
                                    qwMp.eq("unionid",user.getUnionId());
                                    qwMp.eq("mp_type","cy");
                                    qwMp.last("limit 1");
                                    UserMp userMp = userMpService.getOne(qwMp);
                                    if(userMp != null){
                                        WxMsgTemplate template = getTemplateUseReg(record,device,userMp,isSafe);
                                        System.out.println("模板消息：" + template.toString());
                                        String param = JSONUtil.parseObj(template).toString();
                                        String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                                        WxMessage.sendMsg(accessToken,param);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }


    private WxMsgTemplate getTemplateUseReg(DeviceWeldingRecord company,DeviceWelding device, UserMp userMp, int isSafe){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",8);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            if(isSafe == 1){
                miniprogram.put("pagepath","pages/welding/record/index");
            }else{
                miniprogram.put("pagepath","pages/firework/list/index");
            }
            template.setMiniprogram(miniprogram);

//            {{first.DATA}}
//            申请人：{{keyword1.DATA}}
//            申请时间：{{keyword2.DATA}}
//            申请事由：{{keyword3.DATA}}
//            {{remark.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //报警项目
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有新焊机使用申请");
            m.put("first",first);

            //申请人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(company.getWorkerName());
            m.put("keyword1",keyword1);

            //申请时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(device.getUseBeginTime()) + "~" +DateUtil.getTime(device.getUseEndTime()) );
            m.put("keyword2",keyword2);

            //申请理由
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("申请电焊机使用");
            m.put("keyword3",keyword3);

            //贵司存在严重电气火灾安全隐患，为避免造成不可挽救后果，请及时处理！谢谢！
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue("请及时处理！");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }


    @Override
    public void sendWxMsgUseDeviceToProduceManager(DeviceWeldingRecord record, DeviceWelding device, FireWork fireWork, int isSafe) {
        try{
            //当前，只需要给肾器官作业票选中的安全员推送通知
            List<SysUser> sysUsers = new ArrayList<>();
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("user_id",fireWork.getLastCheckSysUserId());
            sysUsers = sysUserService.list(qw);

            if(sysUsers != null && sysUsers.size() > 0){
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && StrUtil.isNotEmpty(user.getUnionId())){
                                QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
                                qwMp.eq("unionid",user.getUnionId());
                                qwMp.eq("mp_type","cy");
                                qwMp.last("limit 1");
                                UserMp userMp = userMpService.getOne(qwMp);
                                if(userMp != null){
                                    WxMsgTemplate template = getTemplateToProduceManager(record,device,userMp,isSafe);
                                    System.out.println("模板消息：" + template.toString());
                                    String param = JSONUtil.parseObj(template).toString();
                                    String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                                    WxMessage.sendMsg(accessToken,param);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplateToProduceManager(DeviceWeldingRecord company,DeviceWelding device, UserMp userMp, int isSafe){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",8);
//        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
//        qwMp.eq("unionid",user.getUnionId());
//        qwMp.eq("mp_type","cy");
//        qwMp.last("limit 1");
//        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            if(isSafe == 1){
                miniprogram.put("pagepath","pages/welding/record/index");
            }else{
                miniprogram.put("pagepath","pages/firework/list/index");
            }
            template.setMiniprogram(miniprogram);

//            {{first.DATA}}
//            申请人：{{keyword1.DATA}}
//            申请时间：{{keyword2.DATA}}
//            申请事由：{{keyword3.DATA}}
//            {{remark.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //报警项目
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有新焊机使用申请");
            m.put("first",first);

            //申请人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(company.getWorkerName());
            m.put("keyword1",keyword1);

            //申请时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(device.getUseBeginTime()) + "~" +DateUtil.getTime(device.getUseEndTime()) );
            m.put("keyword2",keyword2);

            //申请理由
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("申请电焊机使用");
            m.put("keyword3",keyword3);

            //贵司存在严重电气火灾安全隐患，为避免造成不可挽救后果，请及时处理！谢谢！
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue("请及时处理！");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    @Override
    public void sendWxMsgUseFireWorkToProduceManager(FireWork fireWork) {
        try{
            //当前，只需要给肾器官作业票选中的安全员推送通知
            List<SysUser> sysUsers = new ArrayList<>();
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("user_id",fireWork.getLastCheckSysUserId());
            sysUsers = sysUserService.list(qw);

            if(sysUsers != null && sysUsers.size() > 0){
                for(SysUser sysUser : sysUsers){
                    List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                    if(users != null){
                        for (User user :users){
                            if(user != null && StrUtil.isNotEmpty(user.getUnionId())){
                                QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
                                qwMp.eq("unionid",user.getUnionId());
                                qwMp.eq("mp_type","cy");
                                qwMp.last("limit 1");
                                UserMp userMp = userMpService.getOne(qwMp);
                                if(userMp != null){
                                    WxMsgTemplate template = getFireWorkTemplateToProduceManager(fireWork, userMp);
                                    System.out.println("模板消息：" + template.toString());
                                    String param = JSONUtil.parseObj(template).toString();
                                    String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                                    WxMessage.sendMsg(accessToken,param);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getFireWorkTemplateToProduceManager(FireWork fireWork, UserMp userMp){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",8);
//        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
//        qwMp.eq("unionid",user.getUnionId());
//        qwMp.eq("mp_type","cy");
//        qwMp.last("limit 1");
//        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/firework/list/index");
            template.setMiniprogram(miniprogram);

//            {{first.DATA}}
//            申请人：{{keyword1.DATA}}
//            申请时间：{{keyword2.DATA}}
//            申请事由：{{keyword3.DATA}}
//            {{remark.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //报警项目
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            String info = "管理员您好，有新作业票申请";
            if (fireWork.getRecordType() == 1){
                info = "管理员您好，有新受限空间作业票申请";
            }else if(fireWork.getRecordType() == 2){
                info = "管理员您好，有新高空作业票申请";
            }
            first.setValue(info);
            m.put("first",first);

            //申请人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(fireWork.getRegUserName());
            m.put("keyword1",keyword1);

            //申请时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(fireWork.getFireBeginTime()) + "~" +DateUtil.getTime(fireWork.getFireEndTime()) );
            m.put("keyword2",keyword2);

            //申请理由
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            String info2 = "作业票申请";
            if (fireWork.getRecordType() == 1){
                info2 = "受限空间作业票申请";
            }else if(fireWork.getRecordType() == 2){
                info2 = "高空作业票申请";
            }
            keyword3.setValue(info2);
            m.put("keyword3",keyword3);

            //贵司存在严重电气火灾安全隐患，为避免造成不可挽救后果，请及时处理！谢谢！
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue("请及时处理！");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    @Override
    public void sendWxMsgUseDeviceToPianqu(DeviceWeldingRecord record, DeviceWelding device) {
        try{
            Shop company = shopService.findById(device.getShopId());
            if(company != null){
                List<SysUser> pianquUser = new ArrayList<>();
                if(company.getPianquId() > 0){
                    QueryWrapper<SysUser> qw = new QueryWrapper<>();
                    qw.eq("role_id", 4);
                    qw.eq("pianqu_id", company.getPianquId());
                    pianquUser = sysUserService.list(qw);
                }

                if(pianquUser != null && pianquUser.size() > 0){
                    for(SysUser sysUser : pianquUser){
                        List<User> users = userService.selectListByColumn("sys_user_id",sysUser.getUserId());
                        if(users != null){
                            for (User user :users){
                                if(user != null && StrUtil.isNotEmpty(user.getUnionId())){
                                    WxMsgTemplate template = getTemplateUseToPianqu(record,device,user);
                                    System.out.println("模板消息：" + template.toString());
                                    String param = JSONUtil.parseObj(template).toString();
                                    String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                                    WxMessage.sendMsg(accessToken,param);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplateUseToPianqu(DeviceWeldingRecord record,DeviceWelding device, User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",8);
        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
        qwMp.eq("unionid",user.getUnionId());
        qwMp.eq("mp_type","cy");
        qwMp.last("limit 1");
        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/firework/list/index");
            template.setMiniprogram(miniprogram);

//            {{first.DATA}}
//            申请人：{{keyword1.DATA}}
//            申请时间：{{keyword2.DATA}}
//            申请事由：{{keyword3.DATA}}
//            {{remark.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //报警项目
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有新焊机使用申请");
            m.put("first",first);

            //申请人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(record.getWorkerName());
            m.put("keyword1",keyword1);

            //申请时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(device.getUseBeginTime()) + "~" +DateUtil.getTime(device.getUseEndTime()) );
            m.put("keyword2",keyword2);

            //申请理由
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue("申请电焊机使用");
            m.put("keyword3",keyword3);

            //贵司存在严重电气火灾安全隐患，为避免造成不可挽救后果，请及时处理！谢谢！
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue("请及时处理！");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }


    @Override
    public void sendWxMsgFireworkToSafe(FireWork fireWork) {
        try{
            List<User> users = userService.selectListByColumn("sys_user_id",fireWork.getSafeSysUserId());
            if(users != null){
                for (User user :users){
                    if(user != null && StrUtil.isNotEmpty(user.getUnionId())){
                        WxMsgTemplate template = getTemplateFireworkToSafe(fireWork,user);
                        System.out.println("模板消息：" + template.toString());
                        String param = JSONUtil.parseObj(template).toString();
                        String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                        WxMessage.sendMsg(accessToken,param);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getTemplateFireworkToSafe(FireWork fireWork, User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",8);
        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
        qwMp.eq("unionid",user.getUnionId());
        qwMp.eq("mp_type","cy");
        qwMp.last("limit 1");
        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/firework/list/index");
            template.setMiniprogram(miniprogram);

//            {{first.DATA}}
//            申请人：{{keyword1.DATA}}
//            申请时间：{{keyword2.DATA}}
//            申请事由：{{keyword3.DATA}}
//            {{remark.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //报警项目
            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue("管理员您好，有新作业票申请");
            m.put("first",first);

            //申请人
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(fireWork.getRegUserName());
            m.put("keyword1",keyword1);

            //申请时间
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(DateUtil.getTime(fireWork.getFireBeginTime()) + "~" +DateUtil.getTime(fireWork.getFireEndTime()) );
            m.put("keyword2",keyword2);

            //申请理由
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            if(fireWork.getRecordType() == 2){
                keyword3.setValue("高空作业票申请");
            }
            m.put("keyword3",keyword3);

            //贵司存在严重电气火灾安全隐患，为避免造成不可挽救后果，请及时处理！谢谢！
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getSpicalFontColor());
            remark.setValue("请及时处理！");
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }



    /**
     *
     * @param fireWork
     * @param wxWorkerUserId
     */
    @Override
    public void sendWxMsgRegFireWork(FireWork fireWork, List<Integer> wxWorkerUserId) {
        try{
            List<Integer> userId = new ArrayList<>();
            if(wxWorkerUserId.size() > 0){
                userId.addAll(wxWorkerUserId);
            }
//            if(fireWork.getHeaderWxUserId()!=null && fireWork.getHeaderWxUserId() > 0){
//                userId.add(fireWork.getHeaderWxUserId());
//            }
//            if(fireWork.getLastSubmitSysUserId()!=null && fireWork.getLastSubmitSysUserId() > 0){
//                userId.add(fireWork.getHeaderWxUserId());
//            }
            // 高空作业  要推送给安全员
            if(fireWork.getRecordType() == 2 || fireWork.getRecordType() == 1){
                userId.add(fireWork.getSafeWxUseId());
            }

            for (Integer wxUserId : userId){
                User user = userService.findById(wxUserId);
                if(user != null){
                    WxMsgTemplate template = getFireworkRegTemplate(fireWork,user);
                    System.out.println("模板消息：" + template.toString());
                    String param = JSONUtil.parseObj(template).toString();
                    String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                    WxMessage.sendMsg(accessToken,param);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getFireworkRegTemplate(FireWork fireWork, User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",10);
        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
        qwMp.eq("unionid",user.getUnionId());
        qwMp.eq("mp_type","cy");
        qwMp.last("limit 1");
        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/firework/list/index");
            template.setMiniprogram(miniprogram);


//            服务类型 {{thing4.DATA}}
//            联系方式 {{phone_number5.DATA}}
//            提交时间 {{time6.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //服务类型:
            MsgTempData thing4 = new MsgTempData();
            thing4.setColor(wxTemplate.getFontColor());
            if(fireWork.getRecordType() == 0){
                thing4.setValue("动火作业票");
            } else if(fireWork.getRecordType() == 1){
                thing4.setValue("密闭空间作业票");
            } else if(fireWork.getRecordType() == 2){
                thing4.setValue("高空作业票");
            }
            m.put("thing4",thing4);

            //联系方式:
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            SysUser sysUser = sysUserService.getSysUserByUser(user);
            if(sysUser != null){
                keyword2.setValue(sysUser.getMobile());
            }
            m.put("phone_number5", keyword2);

            //提交时间 :
            MsgTempData time6 = new MsgTempData();
            time6.setColor(wxTemplate.getFontColor());
            time6.setValue(DateUtil.getTime(new Date()));
            m.put("time6",time6);

            template.setData(m);
        }
        return template;
    }



    /**
     *
     * @param fireWork
     */
    @Override
    public void sendWxMsgFireWorkCheck(FireWork fireWork) {
        try{
            List<SysUser> allSysUserList = new ArrayList<>();
            List<SysUser> pianquUser = new ArrayList<>();
            Shop company = shopService.findById(fireWork.getRegCompanyId());
            if(company != null) {
                if (company.getPianquId() > 0) {
                    pianquUser = sysUserService.selectListByColumn("pianqu_id", company.getPianquId());
                    allSysUserList.addAll(pianquUser);
                }

//                QueryWrapper<SysUser> qwShengChan = new QueryWrapper<>();
//                qwShengChan.eq("role_id", 5);
//                qwShengChan.eq("shop_id", company.getId());
//                List<SysUser> shengChanList = sysUserService.list(qwShengChan);
//                if (CollUtil.isNotEmpty(shengChanList) && shengChanList.size() > 0) {
//                    allSysUserList.addAll(shengChanList);
//                }
//
//                Department departmentSafe = departmentService.getSafeDepart(fireWork.getRegCompanyId());
//                if(departmentSafe != null) {
//                    QueryWrapper<SysUser> qw = new QueryWrapper<>();
//                    qw.eq("shop_id", fireWork.getRegCompanyId());
//                    qw.eq("dept_id", departmentSafe.getId());
//                    qw.eq("status", 1);
//                    List<SysUser> sysUsers = sysUserService.list(qw);
//                    if (CollUtil.isNotEmpty(sysUsers) && sysUsers.size() > 0) {
//                        allSysUserList.addAll(sysUsers);
//                    }
//                }
            }


            if(allSysUserList != null && allSysUserList.size() > 0) {
                for (SysUser sysUser : allSysUserList) {
                    List<User> users = userService.selectListByColumn("sys_user_id", sysUser.getUserId());
                    if (users != null) {
                        for (User user : users) {
                            if (user != null && StrUtil.isNotEmpty(user.getUnionId())) {

                                WxMsgTemplate template = getFireworkCheckTemplate(fireWork,user);
                                System.out.println("模板消息：" + template.toString());
                                String param = JSONUtil.parseObj(template).toString();
                                String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                                WxMessage.sendMsg(accessToken,param);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getFireworkCheckTemplate(FireWork fireWork, User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",10);
        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
        qwMp.eq("unionid",user.getUnionId());
        qwMp.eq("mp_type","cy");
        qwMp.last("limit 1");
        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/firework/list/index");
            template.setMiniprogram(miniprogram);


//            服务类型 {{thing4.DATA}}
//            联系方式 {{phone_number5.DATA}}
//            提交时间 {{time6.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //服务类型:
            MsgTempData thing4 = new MsgTempData();
            thing4.setColor(wxTemplate.getFontColor());
            if(fireWork.getRecordType() == 0){
                thing4.setValue("动火作业票");
            } else if(fireWork.getRecordType() == 1){
                thing4.setValue("密闭空间作业票");
            } else if(fireWork.getRecordType() == 2){
                thing4.setValue("高空作业票");
            }
            m.put("thing4",thing4);

            //联系方式:
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            SysUser sysUser = sysUserService.getSysUserByUser(user);
            if(sysUser != null){
                keyword2.setValue(sysUser.getMobile());
            }
            m.put("phone_number5", keyword2);

            //提交时间 :
            MsgTempData time6 = new MsgTempData();
            time6.setColor(wxTemplate.getFontColor());
            time6.setValue(DateUtil.getTime(new Date()));
            m.put("time6",time6);

            template.setData(m);
        }
        return template;
    }


    @Override
    public void sendWxMsgSmokeWarning(SmokeAlarmInfo smokeAlarmInfo) {
        try{
            List<Long> sysUserIds = new ArrayList<>();
            //获取安全科
            Department department = departmentService.getSafeDepart(smokeAlarmInfo.getCompanyId());
            if(department != null){
                //查询安全科的人
                List<SysUser> users = sysUserService.selectListByColumn("dept_id", department.getId());
                if(CollUtil.isNotEmpty(users)){
                    for (SysUser sysUser : users){
                        sysUserIds.add(sysUser.getUserId());
                    }
                }
            }

            for (Long sysUserId : sysUserIds){
                List<User> users = userService.selectListByColumn("sys_user_id", sysUserId);
                for (User user : users){
                    WxMsgTemplate template = getSmokeWarningTemplate(smokeAlarmInfo,user);
                    System.out.println("烟感模板消息：" + template.toString());
                    String param = JSONUtil.parseObj(template).toString();
                    String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                    WxMessage.sendMsg(accessToken,param);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("发送失败" + e.getMessage());
        }
    }


    private WxMsgTemplate getSmokeWarningTemplate(SmokeAlarmInfo smokeAlarmInfo, User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",9);
        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
        qwMp.eq("unionid",user.getUnionId());
        qwMp.eq("mp_type","cy");
        qwMp.last("limit 1");
        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

            Map<String,Object> miniprogram = new HashMap<>();
            miniprogram.put("appid",appidCy);
            miniprogram.put("pagepath","pages/message/index");
            template.setMiniprogram(miniprogram);

//            {{first.DATA}}
//            报警时间：{{keyword1.DATA}}
//            地点：{{keyword2.DATA}}
//            设备：{{keyword3.DATA}}
//            报警内容：{{keyword4.DATA}}
//            项目负责人：{{keyword5.DATA}}
//            {{remark.DATA}}

            Map<String, MsgTempData> m = new HashMap<>();
            //报警时间:
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(DateUtil.getTime(smokeAlarmInfo.getCreateTime()));
            m.put("keyword1",keyword1);

            //地点:
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            keyword2.setValue(smokeAlarmInfo.getCompanyName());
            m.put("keyword2", keyword2);

            //设备:
            MsgTempData keyword3 = new MsgTempData();
            keyword3.setColor(wxTemplate.getFontColor());
            keyword3.setValue(smokeAlarmInfo.getDeviceName() + smokeAlarmInfo.getSerialNumber());
            m.put("keyword3", keyword3);


            //报警内容:
            MsgTempData keyword4 = new MsgTempData();
            keyword4.setColor(wxTemplate.getFontColor());
            keyword4.setValue("烟雾报警");
            m.put("keyword4", keyword4);


            //项目负责人:
            MsgTempData keyword5 = new MsgTempData();
            keyword5.setColor(wxTemplate.getFontColor());
            keyword5.setValue(smokeAlarmInfo.getCompanyName() + " 安全员");
            m.put("keyword5", keyword5);


            template.setData(m);
        }
        return template;
    }



    @Override
    public String getAccessToken(String appId,String secret,int type) {
        String access_token = "";
        try{
            Parameter parameter = parameterService.findById(1);
            if(parameter!= null){//
                if(type == 0){// 小程序
                    access_token = parameter.getAccessToken();
                    if(new Date().getTime() > parameter.getAcLastTime().getTime()) {
                        access_token = WxMessage.getACCESSTOKEN(appId, secret);
                        parameter.setAccessToken(access_token);
                        parameter.setAcLastTime(DateUtil.getAfterSecondsByOld(new Date(),7200));
                        parameterService.updateById(parameter);
                    }
                } else if(type == 1){// 琤一数字公众号
                    access_token = parameter.getAccessTokenMpCy();
                    if(new Date().getTime() > parameter.getAcLastTimeCy().getTime()) {
                        access_token = WxMessage.getACCESSTOKEN(appidMpCy, secretMpCy);
                        parameter.setAccessTokenMpCy(access_token);
                        parameter.setAcLastTimeCy(DateUtil.getAfterSecondsByOld(new Date(),7200));
                        parameterService.updateById(parameter);
                    }
                } else if(type == 2){
                    // 菲舍尔 token
                    access_token = parameter.getFsrAccessToken();
                    if(new Date().getTime() > parameter.getFsrLastTokenTime().getTime()) {
                        JSONObject jsonObject = RequestSignUtils.getAccessToken();
                        if(jsonObject!= null){
                            boolean code = jsonObject.getBool("success");
                            if(code){
                                access_token = jsonObject.getJSONObject("result").getStr("access_token");
                                String refresh_token = jsonObject.getJSONObject("result").getStr("refresh_token");
                                parameter.setFsrAccessToken(access_token);
                                parameter.setFsrRefreshToken(refresh_token);
                                parameter.setFsrLastTokenTime(DateUtil.getAfterSecondsByOld(new Date(),6000));
                                parameter.setFsrRefreshTime(DateUtil.getAfterSecondsByOld(new Date(),6000));
                                parameterService.updateById(parameter);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return access_token;
    }

    @Override
    public void sendWxMsgCarYuyue(PickUpRecord pickUpRecord) {
        try {
            Shop shop = shopService.findById(pickUpRecord.getShopId());
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("sys_user_id", shop.getCarManagerSysUserId());
            userQueryWrapper.last("limit 1");
            User user = userService.getOne(userQueryWrapper);
            if (user != null){
                WxMsgTemplate template = getTemplateUseToCarYuyue(pickUpRecord,user);
                System.out.println("车辆预约模板消息：" + template.toString());
                String param = JSONUtil.parseObj(template).toString();
                String accessToken = wxTemplateService.getAccessToken(appidMpCy,secretMpCy,1);
                WxMessage.sendMsg(accessToken,param);
            }else {
                System.out.println("未查询到车辆推送人员");
            }

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("车辆预约失败！"+ e.getMessage());
        }
    }

    private WxMsgTemplate getTemplateUseToCarYuyue(PickUpRecord record, User user){

        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",11);
        QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
        qwMp.eq("unionid",user.getUnionId());
        qwMp.eq("mp_type","cy");
        qwMp.last("limit 1");
        UserMp userMp = userMpService.getOne(qwMp);
        if(userMp != null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");

//            Map<String,Object> miniprogram = new HashMap<>();
//            miniprogram.put("appid",appidCy);
//            miniprogram.put("pagepath","pages/firework/list/index");
//            template.setMiniprogram(miniprogram);

//            预约状态
//            {{phrase3.DATA}}
//            委派人员
//            {{phrase5.DATA}}
//            联系电话
//            {{phone_number9.DATA}}
//            派单日期
//            {{time4.DATA}}
//            服务站点
//            {{thing8.DATA}}

            String recordType = record.getRecordType() == null ? "" : (record.getRecordType() == 0 ? "卸车" :
                    (record.getRecordType() == 1 ? "装车" : ""));
            Map<String, MsgTempData> m = new HashMap<>();
            MsgTempData phrase3 = new MsgTempData();
            phrase3.setColor(wxTemplate.getFontColor());
            phrase3.setValue("车辆预约");
            m.put("phrase3",phrase3);

            MsgTempData phrase5 = new MsgTempData();
            phrase5.setColor(wxTemplate.getFontColor());
            phrase5.setValue(record.getRealName());
            m.put("phrase5",phrase5);

            MsgTempData phone_number9 = new MsgTempData();
            phone_number9.setColor(wxTemplate.getFontColor());
//            phone_number9.setValue(DateUtil.getTime(device.getUseBeginTime()) + "~" +DateUtil.getTime(device.getUseEndTime()) );
            phone_number9.setValue(record.getPhoneNum());
            m.put("phone_number9",phone_number9);

            MsgTempData time4 = new MsgTempData();
            time4.setColor(wxTemplate.getFontColor());
            time4.setValue( DateUtil.getTime(record.getBeginTime()) + "~" +
                    (DateUtil.getTime(record.getEndTime())).replace(record.getPlanDate()+" ", ""));
            m.put("time4",time4);

            Shop shop = shopService.findById(record.getShopId());
            MsgTempData thing8 = new MsgTempData();
            thing8.setColor(wxTemplate.getFontColor());
            thing8.setValue((shop == null ? "" : shop.getShopName()));
            m.put("thing8",thing8);

//            MsgTempData remark = new MsgTempData();
//            remark.setColor(wxTemplate.getSpicalFontColor());
//            remark.setValue("");
//            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

}
